<template>
  <Layout>
    <div class="product-container">
      <!-- 功能入口区域 -->
      <div class="function-area">
        <el-button type="primary" @click="handleCreateProduct">新建商品</el-button>
        <el-button @click="handleExport">导出</el-button>
      </div>

      <!-- 筛选区域 -->
      <div class="filter-area">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="商品名称">
            <el-input 
              v-model="filterForm.productName" 
              placeholder="请输入商品名称/ID" 
              maxlength="60"
              clearable
            />
          </el-form-item>
          <el-form-item label="商品分组">
            <el-cascader
              v-model="filterForm.productGroup"
              :options="productGroupOptions"
              placeholder="全部"
              clearable
            />
          </el-form-item>
          <el-form-item label="商品价格">
            <div class="price-range">
              <el-input 
                v-model="filterForm.minPrice" 
                placeholder="最低售价" 
                type="number"
                min="0"
              />
              <span class="separator">-</span>
              <el-input 
                v-model="filterForm.maxPrice" 
                placeholder="最高售价" 
                type="number"
                min="0"
              />
            </div>
          </el-form-item>
          <el-form-item label="库存">
            <div class="stock-range">
              <el-input 
                v-model="filterForm.minStock" 
                placeholder="最小库存" 
                type="number"
                min="0"
              />
              <span class="separator">-</span>
              <el-input 
                v-model="filterForm.maxStock" 
                placeholder="最大库存" 
                type="number"
                min="0"
              />
            </div>
          </el-form-item>
          <el-form-item label="上架时间">
            <el-date-picker
              v-model="filterForm.shelfTime"
              type="datetime"
              placeholder="请选择时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 状态标签 -->
      <div class="status-tabs">
        <el-tabs v-model="activeTab" @tab-click="handleTabChange">
          <el-tab-pane label="全部" name="all">
            <span class="tab-count">{{ totalCount }}</span>
          </el-tab-pane>
          <el-tab-pane label="上架中" name="onShelf">
            <span class="tab-count">{{ onShelfCount }}</span>
          </el-tab-pane>
          <el-tab-pane label="已下架" name="offShelf">
            <span class="tab-count">{{ offShelfCount }}</span>
          </el-tab-pane>
          <el-tab-pane label="待审核" name="pendingReview">
            <span class="tab-count">{{ pendingReviewCount }}</span>
          </el-tab-pane>
          <el-tab-pane label="审核失败" name="reviewFailed">
            <span class="tab-count">{{ reviewFailedCount }}</span>
          </el-tab-pane>
          <el-tab-pane label="审核通过" name="reviewPassed">
            <span class="tab-count">{{ reviewPassedCount }}</span>
          </el-tab-pane>
          <el-tab-pane label="违规下架" name="violationOffShelf">
            <span class="tab-count">{{ violationOffShelfCount }}</span>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 数据列表 -->
      <div class="product-table">
        <el-table
          :data="productList"
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="商品ID" min-width="280">
            <template #default="scope">
              <div class="product-info">
                <div class="product-image">
                  <el-upload
                    class="product-image-upload"
                    :auto-upload="false"
                    :show-file-list="false"
                    :on-change="(file: any) => handleImageUploadChange(file, scope.row)"
                  >
                    <el-image 
                      :src="getProductImage(scope.row)"
                      fit="cover"
                      :preview-src-list="scope.row.mainImages || []"
                      @error="handleImageError"
                    />
                    <div class="upload-mask">
                      <el-icon><Plus /></el-icon>
                    </div>
                  </el-upload>
                </div>
                <div class="product-details">
                  <div class="product-name">{{ scope.row.name }}</div>
                  <div class="product-id">ID: {{ scope.row.objectId }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="specifications[0].stock" label="库存" width="100">
            <template #default="scope">
              {{ getStockTotal(scope.row) }}
            </template>
          </el-table-column>
          <el-table-column prop="specifications[0].retailPrice" label="售价" width="100">
            <template #default="scope">
              {{ getMinRetailPrice(scope.row) }}
            </template>
          </el-table-column>
          <el-table-column prop="specifications[0].wholesalePrice" label="原价" width="100">
            <template #default="scope">
              {{ getMinWholesalePrice(scope.row) }}
            </template>
          </el-table-column>
          <el-table-column prop="totalSales" label="总销量" width="100" />
          <el-table-column label="商品状态" width="150">
            <template #default="scope">
              <div class="status-tags">
                <!-- 售卖状态 -->
                <el-tag 
                  :type="getSellingStatusType(scope.row.sellingStatus)"
                  size="small"
                  effect="plain"
                >
                  {{ getSellingStatusText(scope.row.sellingStatus) }}
                </el-tag>
                <!-- 审核状态 -->
                <el-tag 
                  :type="getReviewStatusType(scope.row.reviewStatus)"
                  size="small"
                  effect="plain"
                >
                  {{ getReviewStatusText(scope.row.reviewStatus) }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="shelfTime" label="上架时间" width="180" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button 
                link 
                type="primary" 
                size="small" 
                @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-button 
                link 
                :type="scope.row.sellingStatus === 'onShelf' ? 'danger' : 'primary'" 
                size="small" 
                @click="handleToggleShelf(scope.row)"
              >
                {{ scope.row.sellingStatus === 'onShelf' ? '下架' : '上架' }}
              </el-button>
              <el-button 
                link 
                type="danger" 
                size="small" 
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 确认弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="30%"
        center
      >
        <span>{{ dialogContent }}</span>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmDialog">确认</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </Layout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { TabsPaneContext } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getProductList, deleteProduct, shelfProduct, unshelfProduct, exportProducts, updateProduct } from '@/api/product'
import Layout from '@/components/Layout.vue'
import { cosUtil } from '@/utils/cos' // 导入腾讯云COS工具类

// 路由实例
const router = useRouter()
const route = useRoute()

// 加载状态
const loading = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)

// 状态计数
const onShelfCount = ref(0)
const offShelfCount = ref(0)
const pendingReviewCount = ref(0)
const reviewFailedCount = ref(0)
const reviewPassedCount = ref(0)
const violationOffShelfCount = ref(0)

// 当前选中的标签页
const activeTab = ref('all')

// 筛选表单
const filterForm = reactive({
  productName: '',
  productGroup: [] as string[],
  minPrice: '',
  maxPrice: '',
  minStock: '',
  maxStock: '',
  shelfTime: ''
})

// 商品分组选项
const productGroupOptions = ref([
  {
    value: 'all',
    label: '全部'
  },
  {
    value: 'selling',
    label: '销售中'
  },
  {
    value: 'offShelf',
    label: '已下架'
  }
])

// 商品列表数据
const productList = ref([])

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogContent = ref('')
const dialogCallback = ref<() => void>(() => {})

// 获取售卖状态样式
const getSellingStatusType = (status: string) => {
  switch (status) {
    case 'onShelf':
      return 'success'
    case 'offShelf':
      return 'info'
    case 'violationOffShelf':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取售卖状态文本
const getSellingStatusText = (status: string) => {
  switch (status) {
    case 'onShelf':
      return '上架中'
    case 'offShelf':
      return '已下架'
    case 'violationOffShelf':
      return '违规下架'
    default:
      return '未知状态'
  }
}

// 获取审核状态样式
const getReviewStatusType = (status: string) => {
  switch (status) {
    case 'pending':
      return 'warning'
    case 'failed':
      return 'danger'
    case 'passed':
      return 'success'
    default:
      return 'info'
  }
}

// 获取审核状态文本
const getReviewStatusText = (status: string) => {
  switch (status) {
    case 'pending':
      return '待审核'
    case 'failed':
      return '审核失败'
    case 'passed':
      return '审核通过'
    default:
      return '未知状态'
  }
}

// 加载商品列表数据
const loadProductList = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params: any = {
      limit: pageSize.value,
      skip: (currentPage.value - 1) * pageSize.value,
    }

    console.log('请求参数:', params)

    // 添加筛选条件
    if (filterForm.productName) {
      params.name = filterForm.productName
    }

    if (filterForm.productGroup && filterForm.productGroup.length > 0) {
      params.group = filterForm.productGroup[filterForm.productGroup.length - 1]
    }

    if (filterForm.minPrice) {
      params.minPrice = Number(filterForm.minPrice)
    }

    if (filterForm.maxPrice) {
      params.maxPrice = Number(filterForm.maxPrice)
    }

    if (filterForm.minStock) {
      params.minStock = Number(filterForm.minStock)
    }

    if (filterForm.maxStock) {
      params.maxStock = Number(filterForm.maxStock)
    }

    if (filterForm.shelfTime) {
      params.shelfTime = filterForm.shelfTime
    }

    // 根据标签页过滤
    if (activeTab.value !== 'all') {
      if (['onShelf', 'offShelf', 'violationOffShelf'].includes(activeTab.value)) {
        params.sellingStatus = activeTab.value
      } else if (['pendingReview', 'reviewFailed', 'reviewPassed'].includes(activeTab.value)) {
        params.reviewStatus = activeTab.value.replace('review', '').toLowerCase()
      }
    }

    // 调用API获取商品列表
    const response: any = await getProductList(params)
    
    // 打印完整的响应数据，查看实际结构
    console.log('商品列表API响应:', response)
    
    // 处理响应数据 - LeanCloud返回的数据直接在response中，不在data字段中
    productList.value = response.results || []
    
    // 检查每个商品的图片URL
    if (productList.value.length > 0) {
      console.log('图片URL检查:')
      productList.value.forEach((product: any, index: number) => {
        console.log(`商品${index + 1}(${product.name}):`, {
          mainImages: product.mainImages,
          firstImage: product.mainImages?.[0] || '无图片'
        })
      })
    }
    
    totalCount.value = response.count || 0
    
    console.log('处理后的商品列表:', productList.value)
    
    // 更新状态计数 - 这些计数可能需要单独计算
    // 简单计算一下各状态的数量
    const allProducts = response.results || []
    onShelfCount.value = allProducts.filter((item: any) => item.sellingStatus === 'onShelf').length
    offShelfCount.value = allProducts.filter((item: any) => item.sellingStatus === 'offShelf').length
    pendingReviewCount.value = allProducts.filter((item: any) => item.reviewStatus === 'pending').length
    reviewFailedCount.value = allProducts.filter((item: any) => item.reviewStatus === 'failed').length
    reviewPassedCount.value = allProducts.filter((item: any) => item.reviewStatus === 'passed').length
    violationOffShelfCount.value = allProducts.filter((item: any) => item.sellingStatus === 'violationOffShelf').length
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 计算商品总库存
const getStockTotal = (product: any) => {
  // 如果有stock字段（简化版本），直接返回
  if (product.stock !== undefined && product.stock !== null) {
    return Number(product.stock)
  }
  
  // 兼容旧版规格模式
  if (!product.specifications || !Array.isArray(product.specifications)) {
    return 0
  }
  return product.specifications.reduce((total: number, spec: any) => total + (Number(spec.stock) || 0), 0)
}

// 获取商品价格
const getMinRetailPrice = (product: any) => {
  // 如果有price字段（简化版本），直接返回
  if (product.price !== undefined && product.price !== null) {
    return Number(product.price).toFixed(2)
  }
  
  // 兼容旧版规格模式
  if (!product.specifications || !Array.isArray(product.specifications) || product.specifications.length === 0) {
    return '0'
  }
  const prices = product.specifications
    .map((spec: any) => Number(spec.retailPrice) || 0)
    .filter((price: number) => price > 0)
  
  if (prices.length === 0) return '0'
  return Math.min(...prices).toFixed(2)
}

// 获取最低批发价
const getMinWholesalePrice = (product: any) => {
  if (!product.specifications || !Array.isArray(product.specifications) || product.specifications.length === 0) {
    return '0'
  }
  const prices = product.specifications
    .map((spec: any) => Number(spec.wholesalePrice) || 0)
    .filter((price: number) => price > 0)
  
  if (prices.length === 0) return '0'
  return Math.min(...prices).toFixed(2)
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  loadProductList()
}

// 处理重置
const handleReset = () => {
  // 重置所有表单字段
  filterForm.productName = ''
  filterForm.productGroup = []
  filterForm.minPrice = ''
  filterForm.maxPrice = ''
  filterForm.minStock = ''
  filterForm.maxStock = ''
  filterForm.shelfTime = ''
  
  currentPage.value = 1
  loadProductList()
}

// 处理标签页切换
const handleTabChange = (tab: TabsPaneContext) => {
  currentPage.value = 1
  loadProductList()
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadProductList()
}

// 处理每页条数变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  loadProductList()
}

// 处理新建商品
const handleCreateProduct = () => {
  router.push('/product/create')
}

// 处理导出
const handleExport = async () => {
  // 获取选中的商品ID
  const selectedIds = productList.value
    .filter((item: any) => item.selected)
    .map((item: any) => item.objectId)
  
  if (selectedIds.length === 0) {
    ElMessage.warning('请选择要导出的商品')
    return
  }
  
  try {
    // 调用导出API
    await exportProducts(selectedIds)
    
    // 生成文件名
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const hour = String(now.getHours()).padStart(2, '0')
    const minute = String(now.getMinutes()).padStart(2, '0')
    const second = String(now.getSeconds()).padStart(2, '0')
    
    const fileName = `商品导出 ${year}-${month}-${day} ${hour}:${minute}:${second}.xlsx`
    
    ElMessage.success(`已导出文件：${fileName}`)
  } catch (error) {
    console.error('导出商品失败:', error)
    ElMessage.error('导出商品失败')
  }
}

// 处理编辑
const handleEdit = (row: any) => {
  router.push(`/product/edit/${row.objectId}`)
}

// 处理上下架
const handleToggleShelf = async (row: any) => {
  if (row.sellingStatus === 'onShelf') {
    // 下架操作
    showConfirmDialog(
      '操作确认',
      '是否确认下架？',
      async () => {
        try {
          // 调用下架API
          await unshelfProduct(row.objectId)
          ElMessage.success('商品已下架')
          row.sellingStatus = 'offShelf'
          // 重新加载数据
          loadProductList()
        } catch (error) {
          console.error('下架商品失败:', error)
          ElMessage.error('下架商品失败')
        }
      }
    )
  } else {
    // 上架操作
    showConfirmDialog(
      '操作确认',
      '是否确认上架？',
      async () => {
        try {
          // 调用上架API
          await shelfProduct(row.objectId)
          ElMessage.success('商品已上架')
          row.sellingStatus = 'onShelf'
          // 重新加载数据
          loadProductList()
        } catch (error) {
          console.error('上架商品失败:', error)
          ElMessage.error('上架商品失败')
        }
      }
    )
  }
}

// 处理删除
const handleDelete = (row: any) => {
  showConfirmDialog(
    '操作确认',
    '是否确认删除该商品？',
    async () => {
      try {
        // 调用删除API
        await deleteProduct(row.objectId)
        ElMessage.success('商品已删除')
        // 重新加载数据
        loadProductList()
      } catch (error) {
        console.error('删除商品失败:', error)
        ElMessage.error('删除商品失败')
      }
    }
  )
}

// 显示确认弹窗
const showConfirmDialog = (title: string, content: string, callback: () => void) => {
  dialogTitle.value = title
  dialogContent.value = content
  dialogCallback.value = callback
  dialogVisible.value = true
}

// 确认弹窗
const confirmDialog = () => {
  dialogVisible.value = false
  dialogCallback.value()
}

// 获取商品图片
const getProductImage = (product: any) => {
  if (product.mainImages && product.mainImages.length > 0) {
    return product.mainImages[0]
  }
  return 'https://via.placeholder.com/60'
}

// 处理图片加载错误
const handleImageError = () => {
  console.error('图片加载失败')
}

// 处理商品图片更新
const handleUpdateImage = async (row: any, file: File) => {
  try {
    loading.value = true
    // 使用腾讯云COS上传图片
    const imageUrl = await cosUtil.uploadFile(file)
    
    // 更新商品数据
    const mainImages = row.mainImages || []
    if (mainImages.length > 0) {
      mainImages[0] = imageUrl
    } else {
      mainImages.push(imageUrl)
    }
    
    // 调用API更新商品
    await updateProduct(row.objectId, { mainImages })
    
    ElMessage.success('商品图片更新成功')
    // 刷新列表
    loadProductList()
  } catch (error) {
    console.error('更新商品图片失败:', error)
    ElMessage.error('更新商品图片失败: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

// 处理图片上传变更
const handleImageUploadChange = async (file: any, row: any) => {
  if (file.raw) {
    try {
      await handleUpdateImage(row, file.raw)
    } catch (error) {
      console.error('处理图片上传失败:', error)
    }
  }
}

// 页面加载时获取数据
onMounted(() => {
  loadProductList()
})
</script>

<style scoped>
.product-container {
  padding: 0;
}

.function-area {
  margin-bottom: 20px;
}

.filter-area {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.price-range,
.stock-range {
  display: flex;
  align-items: center;
}

.separator {
  margin: 0 5px;
}

.status-tabs {
  margin-bottom: 20px;
}

.tab-count {
  margin-left: 5px;
  font-size: 12px;
  color: #909399;
}

.product-table {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.product-info {
  display: flex;
  align-items: center;
}

.product-image {
  width: 60px;
  height: 60px;
  margin-right: 10px;
  overflow: hidden;
  border-radius: 4px;
}

.product-details {
  flex: 1;
  overflow: hidden;
}

.product-name {
  font-weight: bold;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-id {
  font-size: 12px;
  color: #909399;
}

.status-tags {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.product-image-upload {
  position: relative;
  width: 100%;
  height: 100%;
  cursor: pointer;
}

.upload-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
  color: #fff;
}

.product-image-upload:hover .upload-mask {
  opacity: 1;
}
</style> 